<template>
  <div class="edit">
    <transition name="fade" mode="out-in">
      <keep-alive include="editor">
        <Editor :form-value="articleInfo" @sendOrSave="save"></Editor>
      </keep-alive>
    </transition>
  </div>
</template>

<script>
// 导入 editor 组件
import Editor from '@/components/Editor.vue'
// 从 vuex 中导入辅助函数
import { mapState, mapActions } from 'vuex'
// 导入API接口
import { getArticleByIdAPI } from '@/API/api'
export default {
  // 注册 editoe 组件
  components: {
    Editor
  },
  data() {
    return {
      // 获取的文章信息
      articleInfo: {}
    }
  },
  computed: {
    // 将 仓库的 状态（数据），映射为当前组件的计算属性
    ...mapState('cate', ['cate']),
    ...mapState('tag', ['tag'])
  },
  methods: {
    // 将仓库的异步方法映射为当前组件的方法
    ...mapActions('cate', ['getCateList']),
    ...mapActions('tag', ['getTag']),
    ...mapActions('write', ['addNewActicle', 'updateArticle']),
    // 获取文章信息
    async getArticleInfo() {
      try {
        const { data: res } = await getArticleByIdAPI(this.$route.query.id)
        if (res.status !== 0) return this.$message.error(res.msg)
        // console.log(res)
        this.articleInfo = res.data
        // console.log(this.articleInfo)
      } catch (err) {
        console.log(err.message)
      }
    },
    // 保存修改
    async save(childValue) {
      // console.log(this.formValue)
      if (childValue.title === '') { return this.$message.warning('文章标题不能为空') }
      if (childValue.imgUrl === '') { return this.$message.warning('文章封面图片地址不能为空') }
      if (childValue.describe === '') { return this.$message.warning('文章描述不能为空') }
      if (childValue.content === '') { return this.$message.warning('文章内容不能为空') }
      if (childValue.cateName === '') { return this.$message.warning('请选择文章分类') }
      if (childValue.tagName === '') { return this.$message.warning('请选择文章标签') }
      try {
        // 生成时间
        const date = new Date()
        // 年
        const y = date.getFullYear()
        // 月
        const m = date.getMonth() + 1
        // 日
        const d = date.getDate()
        // 时
        const h = date.getHours()
        // 分
        const mm = date.getMinutes()
        // 秒
        const s = date.getSeconds()
        const nowTime = `${y}-${m}-${d} ${h}:${mm}:${s}`
        childValue.createTime = nowTime
        childValue.id = this.$route.query.id
        console.log(childValue)
        await this.updateArticle(childValue)
        this.getArticleInfo()
        this.$message.success('success')
        console.log(this.articleInfo)
      } catch (err) {
        this.$message.error(err.message)
      }
    }
  },
  created() {
    // console.log(this.$route.query.id)
    this.getArticleInfo()
  }
}
</script>

<style lang="less" scoped></style>
